import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'dart:async';

class VerificationCodeDialog extends StatefulWidget {
  @override
  _VerificationCodeDialogState createState() => _VerificationCodeDialogState();
}

class _VerificationCodeDialogState extends State<VerificationCodeDialog> {
  int _countdownSeconds = 120;
  final List<String> _code = List.filled(6, '');
  final List<FocusNode> _focusNodes = List.generate(6, (index) => FocusNode());
  final List<TextEditingController> _controllers = List.generate(6, (index) => TextEditingController());
  Timer? _timer;
  int _currentFocusIndex = 0; // 跟踪当前聚焦的输入框索引

  @override
  void initState() {
    super.initState();
    _startCountdown();
    _focusNodes[0].requestFocus();

    // 监听焦点变化，更新当前聚焦索引
    for (var i = 0; i < 6; i++) {
      _focusNodes[i].addListener(() {
        if (_focusNodes[i].hasFocus) {
          setState(() {
            _currentFocusIndex = i;
          });
        }
      });
    }
  }

  @override
  void dispose() {
    _timer?.cancel();
    for (var node in _focusNodes) {
      node.dispose();
    }
    for (var controller in _controllers) {
      controller.dispose();
    }
    super.dispose();
  }

  void _startCountdown() {
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        if (_countdownSeconds > 0) {
          _countdownSeconds--;
        } else {
          Navigator.of(context).pop();
          _timer?.cancel();
        }
      });
    });
  }

  void _onCodeChanged(String value, int index) {
    if (value.isNotEmpty) {
      setState(() {
        _code[index] = value;
      });
      // 自动跳到下一个输入框
      if (index < 5) {
        _focusNodes[index + 1].requestFocus();
      }
    }
  }

  // 修复的删除处理逻辑
  void _handleDelete() {
    setState(() {
      // 如果当前输入框有内容，清空当前
      if (_code[_currentFocusIndex].isNotEmpty) {
        _code[_currentFocusIndex] = '';
        _controllers[_currentFocusIndex].clear();
      }
      // 如果当前输入框为空且不是第一个，聚焦到前一个并清空
      else if (_currentFocusIndex > 0) {
        // 移除前一个输入框的内容
        _code[_currentFocusIndex - 1] = '';
        _controllers[_currentFocusIndex - 1].clear();
        // 聚焦到前一个输入框
        _focusNodes[_currentFocusIndex - 1].requestFocus();
      }
    });
  }

  bool _isCodeComplete() {
    return _code.every((char) => char.isNotEmpty);
  }

  void _verifyCode() {
    String code = _code.join();
    Navigator.of(context).pop(code);
  }

  // 构建单个验证码输入框
  Widget _buildCodeInput(int index) {
    return SizedBox(
      width: 40,
      child: RawKeyboardListener(
        // 使用单独的焦点节点来监听键盘事件
        focusNode: FocusNode(canRequestFocus: false),
        onKey: (event) {
          // 检测删除键按下事件
          if (event is RawKeyDownEvent &&
              event.logicalKey == LogicalKeyboardKey.backspace) {
            _handleDelete();
          }
        },
        child: TextField(
          controller: _controllers[index],
          focusNode: _focusNodes[index],
          textAlign: TextAlign.center,
          keyboardType: TextInputType.number,
          maxLength: 1,
          style: const TextStyle(fontSize: 24, letterSpacing: 2),
          decoration: InputDecoration(
            counterText: '', // 隐藏计数器
            enabledBorder: UnderlineInputBorder(
              borderSide: BorderSide(
                color: _focusNodes[index].hasFocus ? Colors.blue : Colors.grey[300]!,
                width: 2,
              ),
            ),
            focusedBorder: UnderlineInputBorder(
              borderSide: const BorderSide(
                color: Colors.blue,
                width: 2,
              ),
            ),
          ),
          onChanged: (value) => _onCodeChanged(value, index),
          onTap: () {
            if (_controllers[index].text.isNotEmpty) {
              // 点击已有内容的输入框时选中内容，方便直接替换
              _controllers[index].selection = TextSelection(
                baseOffset: 0,
                extentOffset: _controllers[index].text.length,
              );
            }
          },
          inputFormatters: [
            FilteringTextInputFormatter.digitsOnly, // 只允许输入数字
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      backgroundColor: Colors.white,
      title: const Center(
        child: Text(
          '请输入验证码',
          style: TextStyle(fontSize: 18, fontWeight: FontWeight.w500),
        ),
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: List.generate(6, (index) => _buildCodeInput(index)),
          ),
          const SizedBox(height: 20),
          SizedBox(
            width: double.infinity,
            height: 36,
            child: ElevatedButton(
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFF4DD0E1),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25),
                ),
                elevation: 0,
              ),
              onPressed: _isCodeComplete() ? _verifyCode : null,

              child: Align(
                alignment: Alignment.center,
                child: Container(
                  width: 200,
                  height: 36,
                  child:   Center(
                    child:  Text(
                      _isCodeComplete() ? '确认' : '${_countdownSeconds}s',
                      style: const TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(10),
      ),
      contentPadding: const EdgeInsets.fromLTRB(24, 20, 24, 12),
    );
  }
}

